package com.cskaoyan.config.shiro.realm;

import com.cskaoyan.bean.po.MarketUser;
import com.cskaoyan.bean.po.MarketUserExample;
import com.cskaoyan.config.shiro.CustomToken;
import com.cskaoyan.mapper.MarketUserMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description: 微信小程序使用的Realm
 * @Author: Pinocao
 * @CreateTime: 2022-11-22  17:16
 * @Version: 1.0
 */
@Component
public class CustomWxRealm extends AuthorizingRealm{
    @Autowired
    MarketUserMapper marketUserMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        CustomToken customToken = (CustomToken) authenticationToken;
        String username = customToken.getUsername();
        MarketUserExample marketUserExample = new MarketUserExample();
        MarketUserExample.Criteria criteria = marketUserExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        criteria.andDeletedEqualTo(false);
        List<MarketUser> marketUsers = marketUserMapper.selectByExample(marketUserExample);
        if (marketUsers.size()==1){
            MarketUser marketUser = marketUsers.get(0);
            return new SimpleAuthenticationInfo(marketUser, marketUser.getPassword(), getName());
        }
        return null;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {


        return null;
    }
}